package com.itown.expo.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.web.servlet.ModelAndView;

import webframe.common.dao.BaseUser;
import webframe.common.helper.ControllerHelper;

import com.itown.expo.controller.base.MyBaseCommandController;
import com.itown.expo.model.EntUserInfo;
import com.itown.expo.model.UserLoginInfo;

public class UserModifyPasswordController extends MyBaseCommandController {

	@Override
	protected ModelAndView handleInner(HttpServletRequest request,
			HttpServletResponse response, Object command)
			throws RuntimeException {
		BaseUser user = ControllerHelper.getUserBySession();
		String oldpass = request.getParameter("oldpass");
		String newpass = request.getParameter("newpass");
		PasswordEncoder encoder = getServiceContainer().getUserService()
				.getPasswordEncoder();
		newpass = encoder.encodePassword(newpass, null);
		oldpass = encoder.encodePassword(oldpass, null);

		Map map = new HashMap();
		if (user instanceof UserLoginInfo) {
			UserLoginInfo ciquser = (UserLoginInfo) user;
			UserLoginInfo old = getServiceContainer().getUserService()
					.findCIQUserById(ciquser.getId());
			if (!old.getPassword().equals(oldpass)) {
				old.setErrorInfo("原始密码错误！");
				map.put("user", old);
				return new ModelAndView(getFailureView(), "map", map);
			}

			old.setPassword(newpass);
			getServiceContainer().getUserService().updateCIQUser(old);
		} else if (user instanceof EntUserInfo) {
			EntUserInfo entuser = (EntUserInfo) user;
			EntUserInfo old = getServiceContainer().getUserService()
					.findEntUserById(entuser.getId());
			if (!old.getPassword().equals(oldpass)) {
				old.setErrorInfo("原始密码错误！");
				map.put("user", old);
				return new ModelAndView(getFailureView(), "map", map);
			}
			old.setPassword(newpass);
			getServiceContainer().getUserService().updateEntUser(old);
		}
		return null;
	}
}
